package corelayer;

import com.sun.org.apache.xpath.internal.operations.Equals;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/*
 * フォーマット:
 *   1:UTF: 送信者ID
 *   2:UTF: 宛先ID
 *   3:UTF: 本文
 */
/**
 * メッセージのデフォルト実装です
 */
public class Message implements IMessage {

    private String sourceID;
    private String destID;
    private String body;

    public Message(String source, String dest, String msgBody) {
        this.sourceID = source;
        this.destID = dest;
        this.body = msgBody;
    }

    @Override
    public void writeTo(DataOutput out) throws IOException {
        out.writeUTF(this.getSourceNodeID());
        out.writeUTF(this.getDestinationNodeID());
        out.writeUTF(this.getBody());
    }

    public static IMessage decode(DataInput in) throws IOException {
        String sender = in.readUTF();
        String dest = in.readUTF();
        String body = in.readUTF();
        return new Message(sender, dest, body);
    }
    
    @Override
    public String getBody() {
        return body;
    }

    @Override
    public String getDestinationNodeID() {
        return this.destID;
    }

    @Override
    public String getSourceNodeID() {
        return this.sourceID;
    }

    @Override
    public IMessage clone() {
        return new Message(this.getSourceNodeID(), this.getDestinationNodeID(), this.getBody());
    }

    @Override
    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }
        if (o == this) {
            return true;
        }
        if (!(o instanceof Message)) {
            return false;
        } else {
            Message msg = (Message)o;
            return msg.getSourceNodeID().equals(this.getSourceNodeID()) &&
                    msg.getDestinationNodeID().equals(this.getDestinationNodeID()) &&
                    msg.getBody().equals(this.getBody());
        }
    }
    
    @Override
    public int hashCode(){
        return (this.getSourceNodeID() == null ? 0 : this.getSourceNodeID().hashCode())
                ^ (this.getDestinationNodeID() == null ? 0 : this.getDestinationNodeID().hashCode())
                ^ (this.getBody() == null ? 0 : this.getBody().hashCode());
    }
}
